<?php
/**
 * Created by PhpStorm.
 * User: leishaofa
 * Date: 2017/7/22
 * Time: 11:48
 * efect:团队订单
 */
class MyOrderAction extends CommonAction{

    /**
     * @auth:leishaofa
     * @date:2017-07-13
     * @efect:我的订单列表
     */
    public function lists(){

        $ordermodel=M('order','f_',C('flashSale'));
        $memberinfo = session('member_info');
        $page=is_numeric($_GET['p'])?$_GET['p']:'';
        $where=" where a.team_id = ".$memberinfo['t_id'];
        $where.=" and a.order_type <> 3";
        if(IS_AJAX && $page){
            $startnumber=($page-1)*C('PAGENUMBER');
            $field="a.*,b.*,c.*";
            $datasql="select ".$field." from f_order as a left join f_user as b on a.u_id = b.u_id  left join f_site as c on a.site_id=c.site_id  ".$where."  order by a.order_type asc , a.ordertime desc limit $startnumber, ".C('PAGENUMBER')."  ";
            $listdata = $ordermodel->query($datasql);
            if (is_array($listdata) && !empty($listdata)) {
                $listdata=array_map(function($val) use ($memberinfo){
                    $val['remark']=json_decode($val['remark'],true);
                    $val['u_field']=json_decode($val['u_field'],true);
                    $val['m_id']=empty($val['m_id']) || $val['m_id']==$memberinfo['m_id'] || $val['order_type']>1?0:1;
                    return $val;
                },$listdata);
                return $this->ajaxReturn(array('code' => 101, 'msg' => "成功", 'data' => $listdata));
            } else {
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "没有数据", 'data' => []));
            }
            exit;
        }
        $resultcountsql="select count(1) as ordersum from f_order as a ".$where." ";
        $resultcount=$ordermodel->query($resultcountsql);
        $this->assign('page',ceil($resultcount[0]['ordersum']/C('PAGENUMBER')));
        $this->assign('type',0);

        C('TOKEN_ON',false);
        $this->display();
    }


    /**
     * @auth:leishaofa
     * @date:2017-07-24
     * @efect: 获取支付链接
     */
    public function goPay(){
        if(is_ajax) {
            $memberinfo = session('member_info');
            $id = is_numeric($_POST['id']) ? $_POST['id'] : 0;
            $type = is_numeric($_POST['is_close']) ? $_POST['is_close'] : 0;
            if (empty($id)) {
                $this->ajaxError("没有获取到订单号");
            }
            $resultcountsql = "select order_url,m_id,site_id,ordertime from f_order where order_id= " . $id . " and team_id = " . $memberinfo['t_id'] . " ";
            $resultdata = M('order', 'f_', C('flashSale'))->query($resultcountsql);
            //用户一点击
            if(!empty($resultdata[0]['m_id']) && $resultdata[0]['m_id']!=$memberinfo['m_id'] && empty($type)){
                $this->ajaxError("订单已锁定");
            }

            /*  $ch = curl_init();
              curl_setopt($ch, CURLOPT_URL, trim($url));
              curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36');
              curl_setopt ($ch,CURLOPT_REFERER,'https://www.adidas.com.cn/customer/account/login/');
              curl_setopt($ch, CURLOPT_HEADER,1);
              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
              curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
              curl_setopt($ch, CURLOPT_AUTOREFERER, true);
              curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
              curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
               $result= curl_exec($ch);*/
            //记录点击支付的记录
            //$m_id = explode(',', $resultdata[0]['m_id']);
            if(empty($resultdata[0]['m_id'])) {
                // array_push($m_id, $memberinfo['m_id']);
                // $m_id = implode(",", $m_id);

                $resultcountsql = "update f_order set m_id=" . $memberinfo['m_id'] . " where order_id= " . $id . " and team_id = " . $memberinfo['t_id'] . " ";
                M('order', 'f_', C('flashSale'))->execute($resultcountsql);
            }

            $postData=array('pythontype'=>'getPay','order_url'=>$resultdata[0]['order_url'],'site_id'=>$resultdata[0]['site_id']);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, C('PYTHONURL'));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post数据
            curl_setopt($ch, CURLOPT_POST, 1);
// post的变量
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            $output = curl_exec($ch);
            curl_close($ch);
            if(preg_match('/^\xEF\xBB\xBF/',$output)){
                $output = substr($output,3);
            }
            $output = json_decode(trim($output),true);
            $array=$output['data'];
            $ret=$output['status'];
            //exec('python ' . dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '\python2\getPay.py "' . $resultdata[0]['order_url'] . '" '.$resultdata[0]['site_id'], $array, $ret);

            if ($ret == 1) {
                // $resultcountsql = "update f_order set order_type=2 where order_id= " . $id . " and team_id = " . $memberinfo['t_id'] . " ";
                // $resultup=M('order', 'f_', C('flashSale'))->execute($resultcountsql);
                $this->ajaxError("脚本未运行",$array);
            } elseif ($ret == 2) {
                $this->ajaxError("脚本运行出错",$array);
            } else {
                if ($array[0] == 'TRADE_HAS_SUCCESS'){
                    $resultcountsql = "update f_order set order_type=2 where order_id= " . $id . " and team_id = " . $memberinfo['t_id'] . " ";
                    $resultup=M('order', 'f_', C('flashSale'))->execute($resultcountsql);
                    $this->ajaxError("已经付款");
                }elseif($array[0] == 'TRADE_HAS_CLOSE'){
                    $resultcountsql = "update f_order set order_type=4 where order_id= " . $id . " and team_id = " . $memberinfo['t_id'] . " ";
                    $resultup=M('order', 'f_', C('flashSale'))->execute($resultcountsql);
                    $this->ajaxError("交易已关闭");
                }elseif((strtotime($resultdata[0]['ordertime'])+2*60*60) < time() ){
                    $resultcountsql = "update f_order set order_type=6 where order_id= " . $id . " and team_id = " . $memberinfo['t_id'] . " ";
                    M('order', 'f_', C('flashSale'))->execute($resultcountsql);
                    $this->ajaxError("订单超时未支付");
                }elseif(filter_var($array[0], FILTER_VALIDATE_URL)){
                    if(!empty($type)){
                        $resultcountsql = "update f_order set m_id='' where order_id= " . $id . " and team_id = " . $memberinfo['t_id'] . " ";
                        M('order', 'f_', C('flashSale'))->execute($resultcountsql);
                    }
                    $data='<img src="' . $array[0] . '"/>';
                    $this->ajaxSuccess("成功", $data);
                }else{
                    $data='<p>出现位置问题，请点击查看支付</p><a href="'.$resultdata[0]['order_url'].'" target="view_window">查看支付状态</a>';
                    $this->ajaxSuccess("成功", $data);
                }

            }
        }
    }

    /**
     * @auth:leishaofa
     * @date:2017-07-25
     * @efect: 确认支付完成
     */
    public function confirmGoPay(){
        if(IS_AJAX){
            $memberinfo = session('member_info');
            $id = is_numeric($_POST['id']) ? $_POST['id'] : 0;
            $resultcountsql = "update f_order set order_type=2 where order_id= " . $id . " and team_id = " . $memberinfo['t_id'] . " ";
            $resultup=M('order', 'f_', C('flashSale'))->execute($resultcountsql);
            if ($resultup) {
                $this->ajaxSuccess("操作成功");
            } else {
                $this->ajaxError("操作失败，订单不存在");
            }
        }
    }
    /**
     * @auth:leishaofa
     * @date:2017-07-25
     * @efect: 团队删除订单
     */
    public function delorder(){
        if(IS_AJAX){
            $memberinfo = session('member_info');
            $id = is_numeric($_POST['keyid']) ? $_POST['keyid'] : 0;
            $resultcountsql = "update f_order set order_type=3 where order_id= " . $id . " and team_id = " . $memberinfo['t_id'] . " ";
            $resultup=M('order', 'f_', C('flashSale'))->execute($resultcountsql);
            if ($resultup) {
                $this->ajaxSuccess("删除成功");
            } else {
                $this->ajaxError("操作失败，订单不存在");
            }
        }
    }
    /**
     * @auth:leishaofa
     * @date:2017-07-25
     * @efect: 团队删除订单
     */
    public function getExpress(){
        if(IS_AJAX){
            $memberinfo = session('member_info');
            $id = is_numeric($_POST['keyid']) ? $_POST['keyid'] : 0;
            if (empty($id)) {
                $this->ajaxError("没有获取到订单号");
            }
            $resultcountsql = "select a.thirdorderid,a.site_id,b.mobile,b.u_eamil,b.u_pwd from f_order as a left join f_user as b on a.u_id=b.u_id where order_id= " . $id . " and team_id = " . $memberinfo['t_id'] . " ";
            $resultdata = M('order', 'f_', C('flashSale'))->query($resultcountsql);

            $postData=array('pythontype'=>'orderInfo','thirdorderid'=>$resultdata[0]['thirdorderid'],'u_eamil'=>$resultdata[0]['u_eamil'],'site_id'=>$resultdata[0]['site_id'],'mobile'=>$resultdata[0]['mobile']);
            // $url = "";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, C('PYTHONURL'));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            // post数据
            curl_setopt($ch, CURLOPT_POST, 1);
            // post的变量
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            $output = curl_exec($ch);
            curl_close($ch);
            if(preg_match('/^\xEF\xBB\xBF/',$output)){
                $output = substr($output,3);
            }
            $output = json_decode(trim($output),true);
            $array=$output['data'];
            $ret=$output['status'];
            if ($ret == 1) {
                $this->ajaxError("未获取到快递单号");
            } elseif ($ret == 2) {
                $this->ajaxError($array);
            } else {
                $list=json_decode($array[0],true);
                $html='';
                $title='';
                $expersnumber='';
                $expers="";
                foreach ($list as $k=>$v){

                    switch ($k) {
                        case "status":
                            $title="订单状态";
                            break;
                        case "company":
                            $title="物流公司";
                            break;
                        case "trackingNumber":
                            $title="快递单号";
                            break;
                        case "trackingUrl":
                            $title="物流信息";
                            $expresshtml=file_get_contents($v);
                            $regex4="/<ul class=.*?>.*?<\/ul>/ism";
                            if(preg_match_all($regex4, $expresshtml, $matches)){
                                $v=implode('',$matches[0]);
                            }
                            break;
                        default:
                            $title="";
                            break;
                    }
                    $html.='<div class="layui-form-item">';
                    $html.='<label class="layui-form-label">'.$title.'</label>';
                    $html.='<div class="layui-input-block">';
                    $html.='<div class="expless">'.$v.'</div></div></div>';

                }
                $updatesql = "update f_order set expresNumber='" . $list['trackingNumber'] . "',expres='".$list['company']."' where order_id= " . $id . " and team_id = " . $memberinfo['t_id'];
                M('order', 'f_', C('flashSale'))->execute($updatesql);
                $this->ajaxSuccess("成功", $html);
            }
        }
    }
    /*
ALTER TABLE `f_order`
ADD COLUMN `expresNumber`  varchar(26) NULL AFTER `ordertime`,
ADD COLUMN `expres`  varchar(16) NULL AFTER `expresNumber`;

    */
    /**
     * @auth:leishaofa
     * @date:2017-07-26
     * @efect: 订单批量处理
     */
    public function batch(){
        if(IS_AJAX){
            $memberinfo = session('member_info');
            $ids=explode(',',$_POST['ids']);
            $ids=array_filter($ids,'is_numeric');
            if(empty($ids)){
                $this->ajaxError("失败");
            }else{
                $iddata=implode(',',$ids);
                $sql="delete from f_order where order_id in (".$iddata.") and team_id =".$memberinfo['t_id']." ";
                $result=M('','',C('flashSale'))->execute($sql);
                if($result){
                    $this->ajaxSuccess("成功");
                }else{
                    $this->ajaxError("失败");
                }
            }
            //print_r($ids);
        }

    }

    /**
     * @auth:leishaofa
     * @date:2017-10-16
     * @efect:导出excel
     */
    public function pushexcel(){
        if(IS_AJAX){
            $memberinfo = session('member_info');
            $model=M('','',C('flashSale'));
            $type=is_numeric($_GET['type'])?$_GET['type']:0;
            if(!empty($_POST)){
                $data['ordertime']=strtotime($_POST['month'])?" r.ordertime like '".$_POST['month']."%' ":'';
                $data['taskrel_id']=array_filter($_POST['task'],'is_numeric')?" r.taskrel_id in (".implode(',',$_POST['task']).") ":'';
                if($type==1){
                    $data['taskrel_id']=" r.order_type in ('2','3') ";
                }
                $data=array_filter($data);
                if(!empty($data)){
                    $where=implode(' and ',$data);
                    $sql = "select thirdorderid,order_price,ordertime,order_name,expresNumber,expres,order_url,order_num,goods_countprice,order_type,remark,b.u_eamil,b.u_pwd from f_order as r left join f_user as b on r.u_id = b.u_id where r.team_id = " . $memberinfo['t_id'] . " and ".$where." order by order_type";

                    $resultexcel = $model->query($sql);
                    $exceldatatitle=array('登录邮箱','密码','订单号','订单时间','商品名称','订单价格','数量','支付状态');
                    if($resultexcel) {
                        foreach($resultexcel as $key=>$val) {
                            $orderother=json_decode($val['remark'],true);
                            unset($val['remark']);
                            switch ($val['order_type']) {
                                case 1:
                                    $ordertype="待支付";
                                    break;
                                case 2:
                                    $ordertype="已付款";
                                    break;
                                case 3:
                                    $ordertype="已付款";
                                    break;
                                case 4:
                                    $ordertype="交易关闭";
                                    break;
                                case 6:
                                    $ordertype="超时未支付";
                                    break;
                                default:
                                    $ordertype="未知状态";
                                    break;
                            }
                            $v=array($val['u_eamil'],$val['u_pwd'],$val['thirdorderid'],$val['ordertime'],$val['order_name'],$val['order_price'],$val['order_num'],$ordertype);
                            if($type==1){
                                if(!in_array("快递公司",$exceldatatitle)){
                                    array_push($exceldatatitle,"快递公司");
                                }
                                array_push($v,empty($val['expres'])?'':$val['expres']);
                                if(!in_array("快递单号",$exceldatatitle)){
                                    array_push($exceldatatitle,"快递单号");
                                }
                                array_push($v,empty($val['expresNumber'])?'':$val['expresNumber']);
                            }else{
                                if(!in_array("支付链接",$exceldatatitle)){
                                    array_push($exceldatatitle,"支付链接");
                                }
                                array_push($v,$val['order_url']);
                            }
                            if(isset($orderother['color']) || in_array("颜色",$exceldatatitle)){
                                if(!in_array("颜色",$exceldatatitle)){
                                    array_push($exceldatatitle,"颜色");
                                }
                                array_push($v,!isset($orderother['color']) || empty($orderother['color'])?'':$orderother['color']);
                            }

                            if(isset($orderother['size'])  || in_array("尺码",$exceldatatitle)){
                                if(!in_array("尺码",$exceldatatitle)) {
                                    array_push($exceldatatitle, "尺码");
                                }
                                array_push($v,!isset($orderother['size']) || empty($orderother['size'])?'':$orderother['size']);
                            }
                            if(isset($orderother['volume'])  || in_array("内存",$exceldatatitle)){
                                if(!in_array("内存",$exceldatatitle)) {
                                    array_push($exceldatatitle, "内存");
                                }
                                array_push($v,!isset($orderother['volume']) || empty($orderother['volume'])?'':$orderother['volume']);
                            }
                            $resultexcel[$key]=$v;
                        };
                        array_unshift($resultexcel,$exceldatatitle);
                        $this->ajaxSuccess("成功",$resultexcel);
                    }else{
                        $this->ajaxError("没有可导出的订单");
                    }

                }else{
                    $this->ajaxError("月份必选");
                }


                exit;
            }
            $month=strtotime($_GET['date'])?$_GET['date']:'';
            if(!empty($month)) {
                $sql = "select order_name,taskrel_id from f_order where team_id = " . $memberinfo['t_id'] . " and ordertime like '$month%'  GROUP BY taskrel_id";
                $result = $model->query($sql);
                $this->ajaxSuccess('成功',$result);
            }

            $this->display();
        }
    }

    /**
     * @auth:leishaofa
     * @date:2017-07-26
     * @efect: 已支付订单列表
     */
    public function paid(){
        $ordermodel=M('order','f_',C('flashSale'));
        $memberinfo = session('member_info');
        $page=is_numeric($_GET['p'])?$_GET['p']:'';
        $where=" where a.team_id = ".$memberinfo['t_id'];
        $where.=" and a.order_type = 2 ";
        if(IS_AJAX && $page){
            $startnumber=($page-1)*C('PAGENUMBER');
            $field="a.*,b.*,c.*";
            $datasql="select ".$field." from f_order as a left join f_user as b on a.u_id=b.u_id  left join f_site as c on a.site_id=c.site_id  ".$where."  order by a.createtime desc limit $startnumber, ".C('PAGENUMBER')."  ";
            $listdata = $ordermodel->query($datasql);
            if (is_array($listdata) && !empty($listdata)) {
                $listdata=array_map(function($val){
                    $val['remark']=json_decode($val['remark'],true);
                    $val['u_field']=json_decode($val['u_field'],true);
                    return $val;
                },$listdata);
                return $this->ajaxReturn(array('code' => 101, 'msg' => "成功", 'data' => $listdata));
            } else {
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "没有数据", 'data' => []));
            }
            exit;
        }
        $resultcountsql="select count(1) as ordersum from f_order as a ".$where." ";
        $resultcount=$ordermodel->query($resultcountsql);
        $this->assign('page',ceil($resultcount[0]['ordersum']/C('PAGENUMBER')));
        $this->assign('type',1);
        C('TOKEN_ON',false);
        $this->display('lists');
    }

}